package com.agileai.esb.smc.controller.monitor;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.esb.smc.bizmoduler.analysis.WebServiceStatManage;
import com.agileai.esb.wsmodel.WSRuntimeAnalysis;
import com.agileai.esb.wsmodel.WSRuntimeStat;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.common.BeanFactory;
import com.agileai.hotweb.controller.core.BaseHandler;
import com.agileai.hotweb.domain.FormSelect;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.StringUtil;

public class WSRuntimeStatListHandler
        extends BaseHandler {
    public WSRuntimeStatListHandler() {
        super();
    }

	public ViewRenderer prepareDisplay(DataParam param){
		
		WebServiceStatManage service = lookupService(WebServiceStatManage.class);
		List<DataRow> appRecords = service.findAppRecords();
		FormSelect appNameSelect = new FormSelect();
		appNameSelect.setKeyColumnName("APP_NAME");
		appNameSelect.setValueColumnName("APP_NAME");
		appNameSelect.putValues(appRecords);
		String appSelect = param.get("appName");
		
		if(StringUtil.isNotNullNotEmpty(param.get("appName"))){
			appNameSelect.setSelectedValue(appSelect);
		}
		
		param.put("appName", appNameSelect);
		this.setAttribute("appName",appNameSelect);	
		
		String serviceId = param.getString("SERVICE_ID");
		String serviceCode = param.getString("SERVICE_NAME");
		String projectName = param.getString("SERVICE_PROJECT");
		
		System.out.println("serviceId is "+serviceId);
		System.out.println("serviceCode is "+serviceCode);
		System.out.println("projectName is "+projectName);
		if(StringUtil.isNotNullNotEmpty(serviceId)){
			this.setAttribute("serviceId",serviceId);
		}
		if(StringUtil.isNotNullNotEmpty(serviceCode)){
			this.setAttribute("serviceCode",serviceCode);	
		}	
		if(StringUtil.isNotNullNotEmpty(projectName)){
			this.setAttribute("projectName",projectName);	
		}
		this.setAttributes(param);
		processPageAttributes(param);
		return new LocalRenderer(getPage());
	}    
    
    protected void processPageAttributes(DataParam param) {
    }
    
	@PageAction
	public ViewRenderer query(DataParam param){
		return prepareDisplay(param);
	}
    
    @PageAction
    public ViewRenderer loadMonitorData(DataParam param){
    	String responseText =null;
    	try {
    		String serviceId = param.getString("serviceId");
        	String projectName = param.getString("projectName");
        	System.out.println("serviceId is "+serviceId);
        	System.out.println("projectName is "+projectName);
        	if(StringUtil.isNotNullNotEmpty(serviceId)&&StringUtil.isNotNullNotEmpty(projectName)){
        		WSRuntimeStat runtimeStat = WSRuntimeAnalysis.geInstance(false).getRuntimeStat(projectName,serviceId);
        		JSONArray jsonArray = new JSONArray();
        		if(runtimeStat != null){
            		JSONObject jsonObject = new JSONObject();
            		jsonObject.put("statId",runtimeStat.getStatId());
            		jsonObject.put("appName",runtimeStat.getAppName());
            		jsonObject.put("serviceId",runtimeStat.getServiceId());
            		jsonObject.put("serviceName",runtimeStat.getServiceName());
            		jsonObject.put("serviceAlias",runtimeStat.getServiceAlias());
            		jsonObject.put("serviceOperation",runtimeStat.getOperationName());
            		jsonObject.put("serviceType",runtimeStat.getServiceType());
            		jsonObject.put("totalCount",runtimeStat.getTotalCount());
            		jsonObject.put("successCount",runtimeStat.getSuccessCount());
            		jsonObject.put("failureCount",runtimeStat.getFailureCount());
            		jsonObject.put("maxRuntime",runtimeStat.getMaxRuntime());
            		jsonObject.put("minRuntime",runtimeStat.getMinRuntime());
            		jsonObject.put("averageRuntime",runtimeStat.getTotalRuntime()/runtimeStat.getTotalCount());
            		jsonArray.put(jsonObject);
        		}
        		responseText = jsonArray.toString();
        	}else{
        		responseText = buildJsonText();
        	}
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
    	return new AjaxRenderer(responseText);
    }

    @PageAction
    public ViewRenderer resetMonitor(DataParam param){
    	String responseText = FAIL;
    	try {
    		WebServiceStatManage webServiceStatManage = (WebServiceStatManage) BeanFactory.instance().getBean("webServiceStatManageService");
    		ConcurrentHashMap<String,WSRuntimeStat> runtimeStats = WSRuntimeAnalysis.geInstance(true).getTransitRuntimeStatMap();
    		webServiceStatManage.insertStatRecords(runtimeStats);
    		responseText = SUCCESS;			
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(),e);
		}
    	return new AjaxRenderer(responseText);
    }    
    
    private String buildJsonText(){
    	String result = null;
    	WSRuntimeStat[] runtimeStatArray = WSRuntimeAnalysis.geInstance(false).getRuntimeStats();
    	JSONArray jsonArray = new JSONArray();
    	try {
        	for (int i=0;i < runtimeStatArray.length;i++){
        		WSRuntimeStat runtimeStat = runtimeStatArray[i];
        		JSONObject jsonObject = new JSONObject();
        		jsonObject.put("statId",runtimeStat.getStatId());
        		jsonObject.put("appName",runtimeStat.getAppName());
        		jsonObject.put("serviceId",runtimeStat.getServiceId());
        		jsonObject.put("serviceName",runtimeStat.getServiceName());
        		jsonObject.put("serviceAlias",runtimeStat.getServiceAlias());
        		jsonObject.put("serviceOperation",runtimeStat.getOperationName());
        		jsonObject.put("serviceType",runtimeStat.getServiceType());
        		jsonObject.put("totalCount",runtimeStat.getTotalCount());
        		jsonObject.put("successCount",runtimeStat.getSuccessCount());
        		jsonObject.put("failureCount",runtimeStat.getFailureCount());
        		jsonObject.put("maxRuntime",runtimeStat.getMaxRuntime());
        		jsonObject.put("minRuntime",runtimeStat.getMinRuntime());
        		jsonObject.put("averageRuntime",runtimeStat.getTotalRuntime()/runtimeStat.getTotalCount());
        		jsonArray.put(jsonObject);
        	}
        	result = jsonArray.toString();
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
    	return result;
    }
    
    protected void initParameters(DataParam param) {

    }
}